<template>
  <div class="main app-container">
    <div class="main-container" ref="shipRef">
      <!--顶部查询表单-->
      <div class="searchBox">
        <div>
          <el-form ref="searchForm" v-model="queryParam" :inline="true" label-position="right" size="mini">
            <el-row v-for="(queryType, index) in queryTypeList" :key="index">
              <el-form-item label="条件一：">
                <el-select v-model="queryType.one" style="width: 150px" value-key="code" clearable filterable @change="queryTypeOneChange">
                  <el-option v-for="(item, index) in queryParamTypeOne" :key="index" :label="item.name" :value="item"></el-option>
                </el-select>
                ：
                <el-input
                  v-if="!queryType.one.isDropDown"
                  clearable
                  v-model="queryParam[queryType.one.code]"
                  style="width: 250px"
                  placeholder="请输入"
                  :disabled="!queryType.one.code"
                ></el-input>
                <el-select
                  v-if="queryType.one.isDropDown"
                  v-model="queryParam[queryType.one.code]"
                  style="width: 250px"
                  clearable
                  filterable
                  multiple
                  :disabled="!queryType.one.code"
                >
                  <el-option v-for="(item, index) in queryType.one.list || []" :key="index" :label="item.name" :value="item.code">
                    <div v-if="queryType.one.code === 'brand'">
                      <span style="float: left; color: #8492a6; font-size: 13px">{{ item.name }}</span>
                      <span style="float: right">{{ item.brandDptName }}</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item style="margin: 0 10px">
                <el-button @click="addQueryCondition" icon="el-icon-circle-plus-outline" circle type="info"></el-button>
                <el-button @click="removeQueryCondition(index)" icon="el-icon-remove-outline" circle type="info"></el-button>
              </el-form-item>
              <el-form-item label="条件二：">
                <el-select v-model="queryType.two" style="width: 150px" value-key="startCode" clearable filterable @change="queryTypeTwoChange">
                  <el-option v-for="(item, index) in queryParamTypeTwo" :key="index" :label="item.name" :value="item"></el-option>
                </el-select>
                ：
                <el-date-picker
                  clearable
                  placeholder="选择开始时间"
                  style="width: 250px"
                  type="date"
                  format="yyyy年MM月dd日"
                  value-format="yyyy-MM-dd"
                  v-model="queryParam[queryType.two.startCode]"
                  :disabled="!queryType.two.name"
                ></el-date-picker>
                -
                <el-date-picker
                  clearable
                  placeholder="选择结束时间"
                  style="width: 250px"
                  type="date"
                  format="yyyy年MM月dd日"
                  value-format="yyyy-MM-dd"
                  v-model="queryParam[queryType.two.endCode]"
                  :disabled="!queryType.two.name"
                ></el-date-picker>
              </el-form-item>
            </el-row>
          </el-form>
        </div>
        <div>
          <el-button @click="searchList" size="mini" type="primary">查询</el-button>
          <el-button @click="clearQueryParam" size="mini" type="danger">清除</el-button>
        </div>
      </div>
      <div style="margin-top: 10px; margin-bottom: 10px">
        <buttonName @clickEvent="clickEvent"></buttonName>
      </div>
      <div>
        <el-form v-model="huData" :inline="true" label-position="right" size="mini">
          <el-form-item label="总实际到货支出(元)：">
            <el-input v-model="huData.actualTotalFreightGSummary" disabled maxlength="32" placeholder size="mini" style="width: 100px"></el-input>
          </el-form-item>
          <el-form-item label="总实际到货收入(元)：">
            <el-input v-model="huData.actualTotalFreightCSummary" disabled maxlength="32" placeholder size="mini" style="width: 100px"></el-input>
          </el-form-item>
          <el-form-item label="总发运吨数(吨)：">
            <el-input v-model="huData.tonnageShippedSummary" disabled maxlength="32" placeholder size="mini" style="width: 100px"></el-input>
          </el-form-item>
          <el-form-item label="总毛利(元)：">
            <el-input v-model="huData.profitSummary" disabled maxlength="32" placeholder size="mini" style="width: 100px"></el-input>
          </el-form-item>
          <el-form-item label="不含税总毛利（元）：">
            <el-input v-model="huData.noTaxProfitSummary" disabled maxlength="32" placeholder size="mini" style="width: 100px"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-table
          :data="shipData"
          :header-cell-style="{ textAlign: 'center' }"
          :height="tableHeight"
          border
          highlight-current-row
          id="ship-table"
          @row-click="rowClick"
          @selection-change="selectChange"
          ref="tableRef"
          :row-style="tableRowStyle"
        >
          <drag-table-header :data="$data" :table-header="tableHeader"></drag-table-header>
        </el-table>
        <div class="block">
          <el-pagination
            :current-page="Pagination.currentPage"
            :layout="Pagination.layout"
            :page-size="Pagination.PageSize"
            :page-sizes="Pagination.pageSizeList"
            :total="Pagination.total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            background
            ref="pagination"
            small
          ></el-pagination>
        </div>
      </div>
    </div>

    <!--修改税率 dialog-->
    <el-dialog
      :close-on-click-modal="false"
      :title="rateDialog.title"
      :visible.sync="rateDialog.show"
      :close-on-press-escape="false"
      @close="rateDialogClose"
      destroy-on-close
      v-dialogDrag
      top="30vh"
      v-el-drag-dialog
      width="20%"
    >
      <div>
        <el-form ref="rateDialogRef" v-model="rateDialog.data" size="mini" label-width="50px">
          <el-form-item label="税率:">
            <el-input placeholder="请输入税率" v-model="rateDialog.data.rate"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="rateDialog.show = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="doRateUpdate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import paginationMixin from '@/mixins/pagination'
import isAuth from '@/mixins/buttonAuth'
import resizeMixin from '@/mixins/resize'
import buttonName from '@/components/buttonName/button-name'
import { fundflowdetailExportExcel, fundflowdetailsQuery, getRefCodesByType, GYSClientList, sugarType, updateWabRate } from '@/request/api'
import scrollChange from '@/utils/onscroll'
import dragTableHeader from '@/components/dragTableHeader'

export default {
  mixins: [isAuth, paginationMixin, resizeMixin],
  name: 'shippingStatus',
  data() {
    return {
      tableHeader: [
        {
          type: 'selection',
          width: 55,
        },
        {
          type: 'index',
          label: '序号',
          width: 55,
        },
        {
          prop: 'cmtContractNo',
          label: '委托书编号（供）',
          width: 200,
        },
        {
          prop: 'cmtSigningTime',
          label: '承接时间',
          width: 100,
        },
        {
          label: '支出部分',
          children: [
            {
              label: '卸货时间',
              prop: 'unloadingTime',
              width: 180,
            },
            {
              label: '供应商',
              prop: 'supplier',
              width: 180,
            },
            {
              label: '单价',
              prop: 'cmtTransportUnitPriceG',
              width: 180,
            },
            {
              label: '支出（元）',
              prop: 'cmtTotalFreightG',
              width: 180,
            },
            {
              label: '实际到货支出金额（含税）',
              prop: 'actualTotalFreightG',
              width: 180,
            },
            {
              label: '不含税金额',
              prop: 'noTaxTotalFreightG',
              width: 180,
            },
          ],
        },
        {
          label: '收入部分',
          children: [
            {
              label: '客户',
              prop: 'client',
              width: 180,
            },
            {
              label: '单价（元）',
              prop: 'cmtTransportUnitPriceC',
              width: 180,
            },
            {
              label: '收入（元）',
              prop: 'cmtTotalFreightC',
              width: 180,
            },
            {
              label: '实际到货收入金额（含税）',
              prop: 'actualTotalFreightC',
              width: 180,
            },
            {
              label: '不含税金额',
              prop: 'noTaxTotalFreightC',
              width: 180,
            },
          ],
        },
        {
          label: '是否开票',
          prop: 'isInvoicing',
          width: 200,
          component: {
            props: ['row', 'data'],
            template: '<span>{{data.codeEnum[row.row.isInvoicing]}}</span>',
          },
        },
        {
          label: '开票时间',
          prop: 'invoicingTime',
          width: 180,
        },
        {
          label: '是否收到发票',
          prop: 'isReceive',
          width: 180,
          component: {
            props: ['row', 'data'],
            template: '<span>{{data.codeEnum[row.row.isReceive]}}</span>',
          },
        },
        {
          label: '收票时间',
          prop: 'receiveTime',
          width: 180,
        },
        {
          label: '承运吨数',
          prop: 'tonnageShipped',
          width: 180,
        },
        {
          label: '毛利',
          prop: 'profit',
          width: 180,
        },
        {
          label: '不含税毛利',
          prop: 'noTaxProfit',
          width: 180,
        },
        {
          label: '是否完成运输',
          prop: 'carryOutTransport',
          width: 180,
          component: {
            props: ['row', 'data'],
            template: '<span>{{data.codeEnum[row.row.carryOutTransport]}}</span>',
          },
        },
        {
          label: '收款日期',
          prop: 'collectDate',
          width: 180,
        },
        {
          label: '付款日期',
          prop: 'paymentDate',
          width: 180,
        },
        {
          label: '跟供应商对账',
          prop: 'reconciliationDate',
          width: 180,
        },
        {
          label: '目的地',
          prop: 'destination',
          width: 180,
        },
      ],
      selectList: [], // 选中列
      rateDialog: {
        show: false,
        title: '',
        data: {
          rate: 0.09, // 税率
        },
      },
      codeEnum: {
        Y: '是',
        N: '否',
      },
      codeList: [
        {
          code: 'Y',
          label: '是',
        },
        {
          code: 'N',
          label: '否',
        },
      ],
      // 发票状态
      invoiceStatus: [
        {
          code: 'i',
          label: '开票',
        },
        {
          code: 'r',
          label: '收到发票',
        },
      ],
      huData: {
        actualTotalFreightGSummary: 0,
        actualTotalFreightCSummary: 0,
        tonnageShippedSummary: 0,
        profitSummary: 0,
        noTaxProfitSummary: 0,
      },
      tableHeight: 200,
      clientList: [],
      supplierList: [],
      statusList: [],
      shipData: [], // 表的数据
      currentData: {}, // 当前行
      // 查询项目下拉 第一组
      queryTypeList: [
        {
          one: {
            name: '',
            brandDptName: '',
            code: '',
            isDropDown: false,
            list: [],
          },
          two: {
            name: '',
            startCode: '',
            endCode: '',
          },
        },
      ],
      queryParamTypeOne: [
        {
          name: '委托书编号',
          code: 'contractNo',
        },
        {
          name: '客户',
          code: 'clients',
          isDropDown: true,
          list: [],
        },
        {
          name: '供应商',
          code: 'suppliers',
          isDropDown: true,
          list: [],
        },
        {
          name: '付款状态',
          code: 'status',
          isDropDown: true,
          list: [],
        },
        {
          name: '是否完成运输',
          code: 'isCompleteTransportation',
          isDropDown: true,
          list: [
            {
              code: 'Y',
              name: '是',
            },
            {
              code: 'N',
              name: '否',
            },
          ],
        },
        {
          name: '发票状态',
          code: 'invoiceStatus',
          isDropDown: true,
          list: [
            {
              code: 'i',
              name: '开票',
            },
            {
              code: 'r',
              name: '收到发票',
            },
          ],
        },
      ],
      // 查询项目下拉 第二组
      queryParamTypeTwo: [
        {
          name: '收款日期',
          startCode: 'receiveDateS',
          endCode: 'receiveDateE',
        },
        {
          name: '付款日期',
          startCode: 'payDateS',
          endCode: 'payDateE',
        },
        {
          name: '承接时间',
          startCode: 'singedStartTime',
          endCode: 'singedEndTime',
        },
        {
          name: '卸货时间',
          startCode: 'xhStartTime',
          endCode: 'xhEndTime',
        },
      ],
      currentQueryTypeOne: {
        name: '',
        brandDptName: '',
        code: '',
        isDropDown: false,
        list: [],
      },
      currentQueryTypeTwo: {
        name: '',
        startCode: '',
        endCode: '',
      },
      queryParam: {
        // 查询条件
        contractNo: '', // 委托书编号
        client: '', // 客户名称
        clients: [],
        supplier: '', // 供应商名称
        suppliers: [],
        singedStartTime: undefined, // 开始时间
        singedEndTime: undefined, // 结束时间
        status: '', // 状态
        payStatus: [],
        xhStartTime: undefined, //卸货开始时间
        xhEndTime: undefined, //卸货结束时间
        isCompleteTransportation: '', // 是否完成运输
        invoiceStatus: '', // 发票状态
        receiveDateS: undefined, // 收款日期开始
        receiveDateE: undefined, // 收款日期结束
        payDateS: undefined, // 付款日期开始
        payDateE: undefined, // 付款日期结束
      },
    }
  },
  components: {
    buttonName,
    dragTableHeader,
  },
  created() {
    this.resize = () => {
      this.tableHeight = this.$refs.shipRef.offsetHeight - 175
    }
  },
  mounted() {
    scrollChange(document.querySelector('#ship-table .el-table__body-wrapper'))
    this.initData()
    this.initClientList()
    this.initSupplierList()
    this.initChargeBillsStatus()
    // this.columnDrop()
  },
  methods: {
    queryList() {
      this.Pagination.currentPage = 1
      this.initData()
    },
    tableRowStyle({ row }) {
      if (this.selectList.includes(row)) {
        return {
          'background-color': '#5786ee',
          color: 'white',
        }
      }
    },
    initData() {
      fundflowdetailsQuery(
        Object.assign(
          {
            index: this.Pagination.currentPage,
            size: this.Pagination.pageSize,
          },
          this.queryParam
        )
      ).then(res => {
        this.huData = res.data
        this.shipData = res.data.data
        this.updatePaginationTotal(res.total)
      })
    },
    getList() {
      this.initData()
    },
    initClientList() {
      sugarType({}).then(res => {
        this.clientList = res.data
        for (let val of this.queryParamTypeOne) {
          if ('clients' === val.code) {
            for (let item of this.clientList) {
              val.list.push({
                name: item.dptName,
                code: item.dptId,
              })
            }
            break
          }
        }
      })
    },
    initSupplierList() {
      GYSClientList({}).then(res => {
        this.supplierList = res.data
        for (let val of this.queryParamTypeOne) {
          if ('suppliers' === val.code) {
            for (let item of this.supplierList) {
              val.list.push({
                name: item.fltName,
                code: item.uuid,
              })
            }
            break
          }
        }
      })
    },
    initChargeBillsStatus() {
      getRefCodesByType('结算单状态').then(res => {
        this.statusList = res.data
        for (let val of this.queryParamTypeOne) {
          if ('status' === val.code) {
            for (let item of this.statusList) {
              val.list.push({
                name: item.rvCmeaning,
                code: item.rvLowValue,
              })
            }
            break
          }
        }
      })
    },
    exportEx() {
      fundflowdetailExportExcel({
        nos: this.selectList.map(item => item.cmtContractNo),
        index: this.Pagination.currentPage,
        size: this.Pagination.pageSize,
      }).then(res => {
        const fileName = decodeURI(res.headers['filename'])
        const reader = new FileReader()
        reader.readAsDataURL(new Blob([res.data]))
        reader.onload = e => {
          let a = document.createElement('a')
          a.download = fileName
          a.href = e.target.result
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        }
        window.parent._$store.dispatch('app/loading_status', false)
      })
    },
    // 打开税率弹窗
    rateUpdate() {
      if (!this.selectList.length) {
        this.$message.error({
          showClose: false,
          message: '至少选中一项',
        })
        return
      }
      this.rateDialog.data.rate = this.selectList[0].wabTaxRate.accSub(1)
      this.rateDialog.show = true
      this.rateDialog.title = '税率修改'
    },
    // 修改税率
    doRateUpdate() {
      const ids = []
      const nos = []
      this.selectList.forEach(value => {
        if (value.wabIds && value.wabIds.length) {
          value.wabIds.forEach(id => {
            ids.push(id)
          })
        } else {
          nos.push(value.cmtContractNo)
        }
      })
      updateWabRate({
        rate: this.rateDialog.data.rate,
        ids,
        nos,
      }).then(() => {
        this.$message.success({
          showClose: true,
          message: '修改成功',
        })
        this.rateDialog.show = false
      })
    },
    // 税率dialog关闭
    rateDialogClose() {
      this.$refs['rateDialogRef'].resetFields()
      this.getList()
    },
    rowClick(val) {
      this.$refs['tableRef'].toggleRowSelection(val)
    },
    selectChange(val) {
      this.selectList = val
    },
    clickEvent(val) {
      switch (val.mdlCode) {
        case 'export':
          this.exportEx()
          break
        case 'rateUpdate':
          this.rateUpdate()
      }
    },
    queryTypeOneChange() {
      const codes = this.queryTypeList.map(item => item.one.code)
      for (let key of Object.keys(this.queryParam)) {
        if (
          !codes.includes(key) &&
          key.toLowerCase().indexOf('start') === -1 &&
          key.toLowerCase().indexOf('end') === -1 &&
          key.toLowerCase().indexOf('date') === -1 &&
          key.toLowerCase().indexOf('time') === -1
        ) {
          this.queryParam[key] = ''
        }
      }
      // this.queryParam.contractNo = '' // 委托书编号
      // this.queryParam.client = '' // 客户名称
      // this.queryParam.supplier = '' // 供应商名称
      // this.queryParam.status = '' // 状态
      // this.queryParam.isCompleteTransportation = '' // 是否完成运输
      // this.queryParam.invoiceStatus = '' // 发票状态
    },
    queryTypeTwoChange() {
      const startCodes = this.queryTypeList.map(item => item.two.startCode)
      const endCodes = this.queryTypeList.map(item => item.two.endCode)
      for (let key of Object.keys(this.queryParam)) {
        if (
          !startCodes.includes(key) &&
          !endCodes.includes(key) &&
          (key.toLowerCase().indexOf('start') !== -1 ||
            key.toLowerCase().indexOf('end') !== -1 ||
            key.toLowerCase().indexOf('date') !== -1 ||
            key.toLowerCase().indexOf('time') !== -1)
        ) {
          this.queryParam[key] = undefined
        }
      }
      // this.queryParam.singedStartTime = undefined // 开始时间
      // this.queryParam.singedEndTime = undefined // 结束时间
      // this.queryParam.xhStartTime = undefined //卸货开始时间
      // this.queryParam.xhEndTime = undefined //卸货结束时间
      // this.queryParam.receiveDateS = undefined // 收款日期开始
      // this.queryParam.receiveDateE = undefined // 收款日期结束
      // this.queryParam.payDateS = undefined // 付款日期开始
      // this.queryParam.payDateE = undefined // 付款日期结束
    },
    clearQueryParam() {
      this.queryTypeOneChange()
      this.queryTypeTwoChange()
      this.currentQueryTypeOne = {
        name: '',
        brandDptName: '',
        code: '',
        isDropDown: false,
        list: [],
      }
      this.currentQueryTypeTwo = {
        name: '',
        startCode: '',
        endCode: '',
      }
    },
    addQueryCondition() {
      this.queryTypeList.push({
        one: {
          name: '',
          brandDptName: '',
          code: '',
          isDropDown: false,
          list: [],
        },
        two: {
          name: '',
          startCode: '',
          endCode: '',
        },
      })
    },
    removeQueryCondition(index) {
      if (index !== 0) {
        this.queryTypeList.splice(index, 1)
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.main {
  //height: calc(100vh - 7rem - 5rem);

  .main-container {
    width: 100%;
    height: 100%;
    .searchBox {
      display: flex;
    }
  }
  .summary-p {
    margin-right: 10px;
    font-size: 16px;
    color: #6cdeff;
  }
}
</style>
